﻿#region <!-- Using Directives -->

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;

#endregion

namespace WordSharpDev
{
	internal static class Root
	{
		public static Object Missing;

		public static readonly DirectoryInfo ApplicationDirectory;

		public static readonly DirectoryInfo TempDirectory;

		static Root()
		{
			Missing = Type.Missing;

			#region <!-- Application directory to be created if not exists -->

			ApplicationDirectory = new DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"LVN Systems\Word Sharp Studio"));

			if (!ApplicationDirectory.Exists) ApplicationDirectory.Create();

			#endregion

			#region <!-- Temp directories to be deleted -->

			var l_Folders = new List<DirectoryInfo>();

			foreach (var l_Folder in ApplicationDirectory.GetDirectories("Temp*"))
			{
				l_Folders.Add(l_Folder);
			}

			foreach (var l_Folder in l_Folders)
			{
				try
				{
					l_Folder.Delete(true);
				}
				catch
				{
				}
			}

			#endregion

			#region <!-- New temp directory -->

			while (true)
			{
				TempDirectory = new DirectoryInfo(Path.Combine(ApplicationDirectory.FullName, String.Format("Temp {0:yyyy-MM-dd} {0:HH-mm-ss}", DateTime.Now)));

				if (!TempDirectory.Exists) { TempDirectory.Create(); break; }

				Thread.Sleep(500);
			}

			#endregion
		}

		public static FileInfo GetTempFile(String p_Name)
		{
			return new FileInfo(Path.Combine(TempDirectory.FullName, p_Name));
		}

		public static DirectoryInfo GetTempSubDir(String p_Name, [Optional] Boolean p_Create)
		{
			var l_Directory = new DirectoryInfo(Path.Combine(TempDirectory.FullName, p_Name));

			if (p_Create && !l_Directory.Exists) l_Directory.Create();

			return l_Directory;
		}

		public static void RunMsBuild(String p_FilePath)
		{
			var l_RegPath = @"SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0";

			var l_RegKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(l_RegPath);

			var l_MsBuildPath = Convert.ToString(l_RegKey.GetValue("MSBuildToolsPath"));

			var l_Info = new ProcessStartInfo(Path.Combine(l_MsBuildPath, "MSBuild.exe"), String.Format(@"/nologo /verbosity:quiet /property:Configuration=Debug ""{0}""", p_FilePath));

			l_Info.CreateNoWindow = false; l_Info.WindowStyle = ProcessWindowStyle.Hidden;

			var l_Process = Process.Start(l_Info);

			l_Process.WaitForExit();
		}
	}
}